package com.hyjx.framework.component.log;

import com.hyjx.framework.common.util.SpringBeanUtil;
import com.hyjx.framework.orm.dao.IBaseDao;
import com.hyjx.framework.service.ConfigManager;

import java.util.ArrayList;
import java.util.List;

/**
 * 访问日志工具类
 *
 * @author dijian
 */
public class LogUtil {
    /**
     * 存储访问日志log对象列表
     */
    private static List<LogBusinessModel> logList = new ArrayList<LogBusinessModel>();
    private static int logNum = 0;
    private static int logBufferSize = 1000;

    static {
        String logbuffersize = ConfigManager.getConfig("logIntereptor.buffersize");
        if (logbuffersize != null && logbuffersize.trim().length() != 0) {
            try {
                logBufferSize = Integer.parseInt(logbuffersize);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 添加访问日志对象
     *
     * @param logModel
     */
    public static void addLog(LogBusinessModel logModel) {
        synchronized (logList) {
            logList.add(logModel);
            logNum++;
            if (logNum >= logBufferSize) {
                synchronized (logList) {
                    List<LogBusinessModel> tempList = new ArrayList<LogBusinessModel>(logNum);
                    tempList.addAll(logList);
                    logList.clear();
                    logNum = 0;
                    LogThread logThread = new LogThread(tempList);
                    logThread.start();
                    tempList = null;
                }
            }
        }
    }
}

class LogThread extends Thread {
    List<LogBusinessModel> tempList = null;

    public LogThread(List<LogBusinessModel> logList) {
        tempList = logList;
    }

    @Override
    public void run() {
        try {
            IBaseDao dao = (IBaseDao) SpringBeanUtil.getBean("baseDao");
            //保存日志
            dao.batchInsertObject(new LogBusinessModel().getModuleName() + ".insert", tempList);
        } catch (Exception ex) {
            System.err.println("LogThread:存储日志信息 -- " + ex.getMessage());
        }
    }
}
